package cn.xtcode.domain.trade.service.settlement.filter;

import cn.xtcode.domain.trade.adapter.repository.ITradeRepository;
import cn.xtcode.domain.trade.model.entity.MarketPayOrderEntity;
import cn.xtcode.domain.trade.model.entity.TradeSettlementRuleCommandEntity;
import cn.xtcode.domain.trade.model.entity.TradeSettlementRuleFilterBackEntity;
import cn.xtcode.domain.trade.service.settlement.factory.TradeSettlementRuleFilterFactory;
import cn.xtcode.types.design.framework.link.model2.handler.ILogicHandler;
import cn.xtcode.types.enums.ResponseCode;
import cn.xtcode.types.exception.AppException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;

/**
 * @author: xt-code
 * @date: 2025/5/12 21:56
 * @description:外部单号校验
 */
@Slf4j
@Service
public class OutTradeNoRuleFilter implements ILogicHandler<TradeSettlementRuleCommandEntity, TradeSettlementRuleFilterFactory.DynamicContext, TradeSettlementRuleFilterBackEntity> {
    @Resource
    private ITradeRepository repository;

    @Override
    public TradeSettlementRuleFilterBackEntity apply(TradeSettlementRuleCommandEntity requestParameter, TradeSettlementRuleFilterFactory.DynamicContext dynamicContext) throws Exception {
        log.info("结算规则过滤-外部单号校验{} outTradeNo:{}", requestParameter.getUserId(), requestParameter.getOutTradeNo());

        //1.判断是否为锁单订单
        // 根据 userId、out_trade_no 从group_buy_order_list获取实体对象，判断是否为锁单订单
        MarketPayOrderEntity marketPayOrderEntity = repository.queryMarketPayOrderEntityByOutTradeNoAndUserId(requestParameter.getUserId(), requestParameter.getOutTradeNo());
        if (null == marketPayOrderEntity) {
            log.info("不存在的外部交易单号或用户已退单，不需要做支付订单结算:{} outTradeNo:{}", requestParameter.getUserId(), requestParameter.getOutTradeNo());
            throw new AppException(ResponseCode.E0104);
        }

        dynamicContext.setMarketPayOrderEntity(marketPayOrderEntity);

        return next(requestParameter, dynamicContext);
    }
}
